<template>
  <div>
    <!-- 筛选列表 -->
    <el-card style="margin-bottom: 20px" id="search">
      <div slot="header" class="header flex">
        <span>筛选列表</span>
        <div class="header_answer">
          <!-- <el-progress
            :text-inside="true"
            :stroke-width="26"
            :percentage="70"
          ></el-progress> -->

          <el-button type="primary" size="mini" @click="checkProgress"
            >检查答案</el-button
          >
        </div>
      </div>
      <div class="text item">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          label-width="90px"
          class="serach_contant"
        >
          <el-form-item label="搜索：">
            <el-input
              v-model="queryParams.searchKey"
              placeholder="考点，机房，姓名，科目"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="所属省份：">
            <el-select
              v-model="queryParams.provinceIds"
              placeholder="搜索省份"
              clearable
              multiple
              size="small"
              @focus="getProvinceName"
              @keyup.enter.native="handleQuery"
            >
              <el-option
                v-for="(item, index) in selectProvince"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="标记状态：">
            <el-select
              v-model="queryParams.marked"
              placeholder="标记状态"
              clearable
              size="small"
              @change="handleQuery"
            >
              <el-option
                v-for="(item, index) in selectStatus"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="处理状态：">
            <el-select
              v-model="queryParams.handle"
              placeholder="处理状态"
              clearable
              size="small"
              @change="handleQuery"
            >
              <el-option
                v-for="(item, index) in handleStatus"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >查询</el-button
            >
            <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            > -->
          </el-form-item>

          <el-form-item>
            <el-upload
              ref="dbUrl"
              name="multipartFile"
              :headers="headers"
              :action="uploaddbAction"
              accept=".db"
              :limit="1"
              :file-list="fileList"
              :on-success="onSuccess"
              :on-progress="handleUploadProgress"
            >
              <el-button icon="el-icon-refresh" size="mini" type="warning"
                >导入DB文件</el-button
              >
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 标签列表 -->
    <el-card>
      <div class="text item">
        <!--  Table-->
        <el-table
          v-loading="loading"
          :data="checkAnswer"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            v-if="allManage"
            type="selection"
            width="55"
            align="center"
          />
          <el-table-column
            type="index"
            width="50"
            align="center"
            label="编号"
          />
          <el-table-column label="省份" align="center" prop="provinceName" />
          <el-table-column
            label="考点"
            align="center"
            prop="examName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="机房"
            align="center"
            prop="examRoomName"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="姓名" align="center" prop="name" />
          <el-table-column label="机号" align="center" prop="pcNo" />
          <el-table-column label="答案" align="center" prop="answerDbMessage" />
          <el-table-column label="科目" align="center" prop="subjectName" />
          <el-table-column
            label="操作"
            align="center"
            width="200"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="cheackMQ(scope.row.studentId, scope.row.subjectId)"
                >查看MQ
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="
                  cheackJournal(
                    scope.row.paperId,
                    scope.row.studentId,
                    scope.row.subjectId
                  )
                "
                >查看日志
              </el-button>
              <el-button
                v-if="scope.row.marked == 0"
                id="btn1"
                ref="btn1"
                size="mini"
                type="text"
                icon="el-icon-folder-checked"
                class="btn_close"
                @click="
                  openNormal(
                    scope.row.marked,
                    scope.row.studentId,
                    scope.row.subjectId
                  )
                "
                >标为正常
              </el-button>
              <el-button
                v-else
                id="btn2"
                ref="btn1"
                size="mini"
                type="text"
                icon="el-icon-folder-checked"
                class="btn_close"
                @click="
                  closeNormal(
                    scope.row.marked,
                    scope.row.studentId,
                    scope.row.subjectId
                  )
                "
                >取消标记
              </el-button>
              <el-button
                v-if="scope.row.answerSource == 1"
                id="btn1"
                ref="btn1"
                size="mini"
                type="text"
                icon="el-icon-folder-checked"
                class="btn_close"
                @click="handleUnusual(scope.row.studentId, scope.row.subjectId)"
                >异常处理
              </el-button>
              <el-button
                v-else
                id="btn2"
                ref="btn1"
                size="mini"
                type="text"
                icon="el-icon-folder-checked"
                class="btn_close"
                disabled
                >已处理
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            align="center"
            :formatter="anStatusFormat"
          />
        </el-table>
      </div>
      <!-- page -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 查看MQ -->
    <el-dialog
      title="MQ检查结果"
      :visible.sync="dialogVisible"
      width="473px"
      :before-close="handleClose"
      center
    >
      <div class="checkMQ" style="width: 100%" v-loading="loadingMq">
        <div style="width: 100%">
          <span>共{{ this.Queid_total }}条</span>
          <table width="100%">
            <thead class="thead">
              <tr>
                <td>que_id</td>
                <td>答案</td>
                <td>que_id</td>
                <td>答案</td>
                <td>que_id</td>
                <td>答案</td>
              </tr>
            </thead>
            <div
              style="width: 100%; max-height: 200px; overflow-y: scroll"
              :queidList="queidList"
            >
              <tbody class="tbody" style="width: 100%">
                <tr v-for="(item, index) in cheackMq" :key="index">
                  <td>{{ item[0] ? item[0]["quesId"] : "" }}</td>
                  <td>{{ item[0] ? item[0]["answer"] : "" }}</td>
                  <td>{{ item[1] ? item[1]["quesId"] : "" }}</td>
                  <td>{{ item[1] ? item[1]["answer"] : "" }}</td>
                  <td>{{ item[2] ? item[2]["quesId"] : "" }}</td>
                  <td>{{ item[2] ? item[2]["answer"] : "" }}</td>
                </tr>
              </tbody>
            </div>
          </table>
        </div>
      </div>
    </el-dialog>
    <!-- 查看日志 -->
    <el-dialog
      class="Journal"
      title="查看日志"
      :visible.sync="dialogVisible1"
      width="40%"
      :before-close="handleClose"
      center
    >
      <!-- <div class="flex btn_journal">
        <el-button
          type="primary"
          size="mini"
          class="btn_journal"
          @click="jonrnalExport"
          >导出日志答案</el-button
        >
      </div> -->

      <div class="checkMQ" style="width: 100%" v-loading="loadingJournal">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <template v-for="(item, index) in tabItem">
            <el-tab-pane
              :key="index"
              v-if="index.indexOf('_length') == -1"
              :label="`机号${index.replace(/号/, '')}（${
                active_length[index]
              }）`"
              :name="index"
            >
              <div class="flex btn_journal">
                <el-button
                  type="primary"
                  size="mini"
                  class="btn_journal"
                  @click="jonrnalExport(index)"
                  >导出日志答案</el-button
                >
              </div>

              <el-table
                v-if="item[0]['message'] != '没有文件'"
                :data="item"
                height="250"
                border
                style="width: 100%"
                align="center"
              >
                <el-table-column label="机号" width="50"
                  >{{ index }}
                </el-table-column>
                <el-table-column prop="subjectName" label="科目">
                </el-table-column>
                <el-table-column prop="time" label="时间"> </el-table-column>
                <el-table-column prop="quesId" label="que_id" width="50">
                </el-table-column>
                <el-table-column prop="action" label="操作" width="50">
                </el-table-column>
                <el-table-column prop="answer" label="信息"> </el-table-column>
              </el-table>
              <div v-else>该考生无数据</div>
            </el-tab-pane>
          </template>
        </el-tabs>
      </div>
    </el-dialog>
    <!-- 异常处理 -->
    <el-dialog
      title="异常处理"
      :visible.sync="dialogVisible4"
      width="40%"
      :before-close="handleClose"
      :data="check"
      center
    >
      <el-radio-group v-model="status">
        <el-radio
          v-for="(item, index) in check"
          :key="index"
          :label="item.value"
        >
          {{ item.label }}</el-radio
        >
      </el-radio-group>
      <span slot="footer" class="dialog-footer">
        <el-button>取消</el-button>
        <el-button type="primary" @click="makrSure()">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import Cookies from "js-cookie";
import fileDownload from "js-file-download";
import {
  checkAnswer,
  getProvince,
  changeMQ,
  cheackMq,
  updateUnusual,
  cheackJournal,
  currentCheckTips, //检查答案总进度
  exportJournal, //导出日志答案
} from "@/api/toolsystem/answers";

export default {
  name: "testOver",
  props: {
    anStatusList: Array, // 算分答案状态列表
  },
  data() {
    return {
      tabItem: {},
      // 遮罩层
      loading: true,
      loadingMq: true,
      loadingJournal: true,
      // 选中数组(批量处理)
      ids: [],
      statuss: [],
      subjectIds: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 是否显示弹出层
      open: false,
      // 筛选省
      selectProvince: [],
      // 表单参数
      form: {},
      // 更改状态
      selectStatus: [
        {
          label: "未标记",
          value: 0,
        },
        {
          label: "已标记",
          value: 1,
        },
      ],
      // 处理状态
      handleStatus: [
        {
          label: "未处理",
          value: 1,
        },
        {
          label: "已处理",
          value: 2,
        },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        marked: 0,
        handle: 1,
        provinceIds: [],
        searchKey: null,
      },
      //导入DB文件arry
      fileList: [],
      //显示批量管理
      allManage: false,
      btnText: "批量管理",
      //   申请时间
      value1: "",
      // 参考资质列表
      checkAnswer: [],
      stuname: "取消标记",
      //查看MQ
      cheackMq: "",
      // 查看Mq
      quesId: [],
      cAnswer: [],
      dialogVisible: false,
      cheackQueid: [],
      Queid_total: "",
      queidList: [],
      // 下载入库返回的进度
      msg: "",
      //查看日志
      dialogVisible1: false,
      indexpaperId: "",
      indexstudentId: "",
      indexsubjectId: "",
      //处理异常
      dialogVisible4: false,
      diffstudentId: "",
      diffsubjectId: "",
      // 处理异常
      check: [
        {
          label: "以MQ为准",
          value: 2,
        },
        {
          label: "以日志为准",
          value: 3,
        },
        {
          label: "手工拼接",
          value: 4,
        },
      ],
      status: "",
      // 有日志时第一个tab
      activeName: "1",
      active_length: {},
      // db上传
      uploaddbAction:
        process.env.VUE_APP_BASE_API + "/tools-checkanswer/uploadDb",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
    };
  },
  created() {
    // 获取列表
    const pageNum = Cookies.get("tool_pageNum");
    const pageSize = Cookies.get("tool_pageSize");
    // console.log(pageSize, pageNum);
    if (pageNum) {
      this.queryParams.pageNum = Number(pageNum);
    }
    if (pageSize) {
      this.queryParams.pageSize = Number(pageSize);
    }
    this.getList();
    // this.gettt()
  },
  watch: {
    "queryParams.pageNum"(val) {
      console.log(val);
      Cookies.set("tool_pageNum", val);
    },
    "queryParams.pageSize"(val) {
      console.log(val);
      Cookies.set("tool_pageSize", val);
    },
  },
  methods: {
    gettt() {
      // let aa=[1,1,2,2,3]
      // let b=new Set(aa)
      // aa.add(1)
      // aa.add(1)
      // aa.add(2)
      // console.log(b.size,'111')
    },
    // 算分状态字典翻译
    anStatusFormat(row, column) {
      return this.selectDictLabel(this.anStatusList, row.answerSource);
    },
    // 获取筛选的省份和城市
    getProvinceName() {
      getProvince().then((res) => {
        this.selectProvince = res;
      });
    },
    // 检查答案按钮进度条
    checkProgress() {
      currentCheckTips().then((res) => {
        console.log(res.msg);
        if (res.code != 200) {
          return this.msgInfo(res.msg);
        }
        return this.msgInfo(res.msg);
        // this.percentage = Number(res.msg) * 100;
      });
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // console.log(this.queryParams, "11");
      this.getList();
    },
    // 上传db文件
    onSuccess(res, file) {
      // console.log(res, "111");
      if (res.code != 200) {
        return this.msgInfo(res.msg);
      }
      this.fileList[0] = {
        name: file.name,
        url: res,
      };
      this.$refs["dbUrl"].clearFiles(); //上传成功之后清除历史记录
      return this.msgInfo(res.msg);
    },

    // 文件上传中处理
    handleUploadProgress(event, file, fileList) {

    },

    // 获取答案list
    getList() {
      this.loading = true;
      let obj = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        marked: this.queryParams.marked,
        handle: this.queryParams.handle,
        searchKey: this.queryParams.searchKey,
      };

      checkAnswer(obj, this.queryParams.provinceIds)
        .then((response) => {
          // console.log(response, "joinlist");
          if (response.code != 200) {
            this.loading = false;
            return;
          }
          this.checkAnswer = response.rows;
          // console.log(this.teststieList)
          this.total = response.total;
          // console.log(this.total)
          this.loading = false;
        })
        .catch((error) => {
          this.loading = false;
          // console.log(error);
        });
    },

    //批量管理
    allMange() {
      this.allManage = !this.allManage;
      if (this.allManage == true) {
        this.btnText = "完成管理";
      } else if (this.allManage == false) {
        this.btnText = "批量管理";
      }
    },

    // 批量标记MQ
    batchMQ(statuss, ids, subjectIds) {
      // console.log(this.ids);
      if (this.ids.length <= 0) {
        return this.msgInfo("请选择需要标记的选项");
      }
      this.openNormal(
        this.statuss.join(","),
        this.ids.join(","),
        this.subjectIds.join(",")
      );
    },

    // 查看MQ
    cheackMQ(studentId, subjectId) {
      this.dialogVisible = true;
      this.loadingMq = true;
      cheackMq(studentId, subjectId)
        .then((res) => {
          if (res.code != 200) {
            this.loadingMq = false;
            // return this.res.msg;
          }
          // console.log(res);
          // 取所有的que_id
          this.cheackQueid = res.rows;
          this.Queid_total = res.total;
          this.cheackQueid.map((item) => {
            this.queidList.push(item.quesId);
            // console.log(this.queidList);
          });
          let size = res.total % 3 == 0 ? res.total / 3 : res.total / 3 + 1;
          let cheackMq = res.rows;
          let newArr = [];
          let [start, end, result] = [null, null, []];
          for (let i = 0; i < size; i++) {
            start = i * 3;
            end = start + 3;
            newArr.push(cheackMq.slice(start, end));
          }
          this.cheackMq = newArr;
          // console.log(this.cheackMq);
          if (this.cheackMq.length == 0) {
            this.dialogVisible = false;
            return this.msgInfo("该考生无数据");
          }
          this.loadingMq = false;
        })
        .catch((error) => {
          this.loadingMq = false;
        });
    },
    handleClose(done) {
      done();
    },
    // 查看日志
    cheackJournal(paperId, studentId, subjectId) {
      // console.log(paperId,studentId, subjectId)
      this.dialogVisible1 = true;
      this.loadingJournal = true;
      cheackJournal(paperId, studentId, subjectId)
        .then((res) => {
          // console.log(res);
          if (res.code != 200) {
            this.loadingJournal = true;
            // return this.msgError(res.msg)
          }
          this.indexpaperId = paperId;
          this.indexstudentId = studentId;
          this.indexsubjectId = subjectId;
          this.tabItem = JSON.parse(res.data);
          // console.log(this.tabItem);
          // console.log(res.data);
          this.activeName = Object.keys(this.tabItem)[0];
          let active_length = {};
          for (let key in this.tabItem) {
            if (key.indexOf("_length") == -1) {
              let key_i = key.replace(/号/, "") + "_length";
              let length;
              if (this.tabItem.hasOwnProperty(key_i)) {
                length = this.tabItem[key_i][0]["message"];
              } else {
                length = 0;
              }
              active_length[key] = length;
              // console.log(this.tabItem[key][0]["message"] == "没有文件")
              // if (
              //   length == 1 &&
              //   this.tabItem[key][0]["message"] == "没有文件"
              // ) {
              //   active_length[key] = 0;
              // } else {
              //   active_length[key] = length;
              // }
            }
          }
          this.active_length = active_length;
          // console.log(Object.keys(this.tabItem)[0]);
          this.loadingJournal = false;
        })
        .catch((error) => {
          this.loadingJournal = false;
        });
    },
    // 切换日志tabs
    handleClick(tab, event) {
      // console.log(tab, event);
    },

    /** 日志答案导出 */
    jonrnalExport(index) {
      exportJournal(
        this.indexpaperId,
        this.indexstudentId,
        this.indexsubjectId,
        index
      )
        .then((res) => {
          // console.log(res);
          fileDownload(res, `日志答案下载.xlsx`);
        })
        .catch(() => {});
    },

    /** 标记正常操作 */
    openNormal(status, studentId, subjectId) {
      this.$confirm("是否标记为正常?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then(() => {
        changeMQ(1, studentId, subjectId)
          .then((res) => {
            if (res.code != 200) {
              return this.msgError(res.msg);
            }
            this.getList();
          })
          .catch((error) => {
            this.loading = false;
          });
      });
    },
    closeNormal(status, studentId, subjectId) {
      console.log(status, studentId, subjectId);
      this.$confirm("是否取消标记?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then(() => {
        changeMQ(0, studentId, subjectId)
          .then((res) => {
            if (res.code != 200) {
              return this.msgError(res.msg);
            }
            this.getList();
          })
          .catch((error) => {
            this.loading = false;
          });
      });
    },
    // 处理异常
    handleUnusual(studentId, subjectId) {
      // console.log(studentId, subjectId);
      this.dialogVisible4 = true;
      this.diffstudentId = studentId;
      this.diffsubjectId = subjectId;
    },
    makrSure() {
      // console.log(this.status, studentId, subjectId);
      if (this.status == "") {
        return this.msgInfo("请选择");
      }
      updateUnusual(this.status, this.diffstudentId, this.diffsubjectId)
        .then((res) => {
          if (res.code == 500) {
            this.dialogVisible4 = false;
            return this.msgError(res.msg);
          }
          this.getList();
          this.dialogVisible4 = false;
        })
        .catch((error) => {
          this.loading = false;
        });
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection);
      let statuss = [];
      let ids = [];
      let subjectIds = [];
      selection.forEach((item) => {
        statuss.push(item.answerSource);
        ids.push(item.studentId);
        subjectIds.push(item.subjectId);
      });
      this.statuss = statuss;
      this.ids = ids;
      this.subjectIds = subjectIds;
      // console.log(this.ids);
      this.multiple = !selection.length;
    },
  },
};
</script>
<style lang="scss" scoped>
/*@import "@/assets/styles/card.scss";*/
// bannerlist图标的大小
.flex {
  display: flex;
}
.header {
  justify-content: space-between;
}
::-webkit-scrollbar {
  display: none;
}

// 查看MQ
.checkMQ {
  table {
    border-collapse: collapse;
    border-top: 1px solid #000;
    border-left: 1px solid #000;
    .thead {
      display: flex;
      tr {
        flex: 1;
        display: flex;
        td {
          flex: 1;

          text-align: center;
          border-right: 1px solid #000;
          border-bottom: 1px solid #000;
        }
      }
    }
    .tbody {
      tr {
        display: flex;

        td {
          width: 71px;
          flex: 1;
          text-align: center;
          border-right: 1px solid #000;
          border-bottom: 1px solid #000;
        }
      }
    }
  }
}
// 查看日志
.Journal {
  // position: relative;
  .el-dialog__body {
    padding: 10px 25px 25px;
  }
  .btn_journal {
    // position: absolute;
    // right: 27px;
    justify-content: flex-end;
  }
}
.aa {
  font-size: 20px;
}
.line {
  border-bottom: 1px solid #c0c4cc;
  padding: 20px 0;
}

// search
#search .serach_contant {
  margin-top: 20px;
}
//批量管理
.allManage {
  justify-content: space-between;

  .btnManage {
    justify-content: flex-end;
  }
}
</style>
